<?php
namespace app\admin\controller;

/**
 * 后台菜单
 * Class Menu
 */
class MenuController extends BaseController {

	protected function _initialize() {
		parent::_initialize();
		if(session('ADMIN.id') !=1){
			$this->error('没有权限');
		}
		$admin_menu_list = db('auth_rule')->order('sort ASC,id ASC')->select();
		$admin_menu_level_list = array2level($admin_menu_list);
		$this->assign('admin_menu_level_list', $admin_menu_level_list);
	}

	/**
	 * 后台菜单
	 * @return mixed
	 */
	public function index() {
		return $this->fetch();
	}

	/**
	 * 保存菜单
	 */
	public function add($pid = '') {
		if ($this->request->isPost()) {
			$data = $this->request->post();
			$validate = $this->validate($data, 'AuthRule');
			if ($validate !== true) {
				$this->error($validate);
			}
			if (db('auth_rule')->insert($data)) {
				$this->success('保存成功');
			} else {
				$this->error('保存失败');
			}
		} else {
			return $this->fetch('add', array('pid' => $pid));
		}
	}

	/**
	 * 更新菜单
	 * @param $id
	 */
	public function update($id) {
		if ($this->request->isPost()) {
			$data = $this->request->post();
			$validate = $this->validate($data, 'AuthRule');
			if ($validate !== true) {
				$this->error($validate);
			}
			if (db('auth_rule')->update($data, $id) !== false) {
				$this->success('更新成功');
			} else {
				$this->error('更新失败');
			}
		} else {
			$admin_menu = db('auth_rule')->find($id);
			return $this->fetch('update', array('admin_menu' => $admin_menu));
		}
	}

}
